import { Component } from '../core/Component.js';

/**
 * 文本组件
 */
export class Text extends Component {
  constructor(props = {}) {
    super(props);
    this.text = props.text || '';
    this.tag = props.tag || 'p'; // 支持不同的HTML标签：p, h1, h2, h3, span等
    this.style = props.style || {};
  }

  /**
   * 设置文本内容
   * @param {string} text 新的文本内容
   */
  setText(text) {
    this.text = text;
    if (this.element) {
      this.element.textContent = text;
      console.log('Text组件文本已更新为:', text);
    }
  }

  /**
   * 重写update方法，避免重新创建DOM元素
   */
  update() {
    if (this.element) {
      this.applyStyle();
    }
  }

  applyStyle() {
    if (!this.element) return;
    
    // 基础样式
    this.element.style.margin = '8px 0';
    this.element.style.lineHeight = '1.5';
    this.element.style.wordWrap = 'break-word';
    
    // 根据标签类型设置默认样式
    switch (this.tag) {
      case 'h1':
        this.element.style.fontSize = '2em';
        this.element.style.fontWeight = 'bold';
        this.element.style.margin = '16px 0';
        break;
      case 'h2':
        this.element.style.fontSize = '1.5em';
        this.element.style.fontWeight = 'bold';
        this.element.style.margin = '14px 0';
        break;
      case 'h3':
        this.element.style.fontSize = '1.2em';
        this.element.style.fontWeight = 'bold';
        this.element.style.margin = '12px 0';
        break;
      case 'span':
        this.element.style.display = 'inline';
        this.element.style.margin = '0';
        break;
      default: // p
        this.element.style.fontSize = '16px';
        break;
    }
    
    // 主题样式
    if (this.theme && this.theme.mode) {
      if (this.theme.mode === 'dark') {
        this.element.style.color = this.theme.textColor || '#ffffff';
      } else {
        this.element.style.color = this.theme.textColor || '#333333';
      }
    } else {
      // 默认样式
      this.element.style.color = '#333333';
    }
    
    // 自定义样式（覆盖主题样式）
    for (const [key, value] of Object.entries(this.style)) {
      this.element.style[key] = value;
    }
  }

  render() {
    this.element = document.createElement(this.tag);
    this.element.textContent = this.text;
    
    this.applyStyle();
    return this.element;
  }
} 